/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ajouroid.smartcoworker;

import java.util.ArrayList;
import android.app.Dialog;
import android.content.Context;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

public class ColorPickerDialog extends Dialog {

	public interface OnAttributeChangedListener {
		void attributeChanged(Paint paint);
	}

	private OnAttributeChangedListener mListener;
	private static Paint mChangedPaint;
	private static Paint mCenterPaint;

	private static SeekBar mColorSeekAlpha;
	private static SeekBar mColorSeekRed;
	private static SeekBar mColorSeekBlue;
	private static SeekBar mColorSeekGreen;
	private static SeekBar mThickSeek;

	private static class ColorPickerView extends View {
		private Paint mPaint;
		private final int[] mColors;

		ColorPickerView(Context c, int color) {
			super(c);
			mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF,
					0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 };
			Shader s = new SweepGradient(0, 0, mColors, null);

			mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
			mPaint.setShader(s);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeWidth(32);

			mColorSeekAlpha.setOnSeekBarChangeListener(ColorSeekbarlistner);
			mColorSeekRed.setOnSeekBarChangeListener(ColorSeekbarlistner);
			mColorSeekBlue.setOnSeekBarChangeListener(ColorSeekbarlistner);
			mColorSeekGreen.setOnSeekBarChangeListener(ColorSeekbarlistner);

			mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
			mCenterPaint.setColor(color);
			mCenterPaint.setStrokeWidth(5);
		}

		private boolean mTrackingCenter;
		private boolean mHighlightCenter;

		private SeekBar.OnSeekBarChangeListener ColorSeekbarlistner = new OnSeekBarChangeListener() {

			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				int seekA = mColorSeekAlpha.getProgress();
				int seekR = mColorSeekRed.getProgress();
				int seekG = mColorSeekGreen.getProgress();
				int seekB = mColorSeekBlue.getProgress();
				mChangedPaint.setColor(Color.argb(seekA, seekR, seekG, seekB));
				mCenterPaint.setColor(mChangedPaint.getColor());
				invalidate();
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
			}
		};

		@Override
		protected void onDraw(Canvas canvas) {
			float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;

			canvas.translate(CENTER_X, CENTER_X);

			canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
			canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);

			if (mTrackingCenter) {
				int c = mCenterPaint.getColor();
				mCenterPaint.setStyle(Paint.Style.STROKE);

				if (mHighlightCenter) {
					mCenterPaint.setAlpha(0xFF);
				} else {
					mCenterPaint.setAlpha(0x80);
				}
				canvas.drawCircle(0, 0,
						CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
						mCenterPaint);

				mCenterPaint.setStyle(Paint.Style.FILL);
				mCenterPaint.setColor(c);
			}
		}

		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
		}

		private static final int CENTER_X = 100;
		private static final int CENTER_Y = 100;
		private static final int CENTER_RADIUS = 32;
		
		private int ave(int s, int d, float p) {
			return s + java.lang.Math.round(p * (d - s));
		}

		private int interpColor(int colors[], float unit) {
			if (unit <= 0) {
				return colors[0];
			}
			if (unit >= 1) {
				return colors[colors.length - 1];
			}

			float p = unit * (colors.length - 1);
			int i = (int) p;
			p -= i;
			// now p is just the fractional part [0...1) and i is the index
			int c0 = colors[i];
			int c1 = colors[i + 1];
			int a = ave(Color.alpha(c0), Color.alpha(c1), p);
			int r = ave(Color.red(c0), Color.red(c1), p);
			int g = ave(Color.green(c0), Color.green(c1), p);
			int b = ave(Color.blue(c0), Color.blue(c1), p);
			mColorSeekAlpha.setProgress(a);
			mColorSeekRed.setProgress(r);
			mColorSeekBlue.setProgress(b);
			mColorSeekGreen.setProgress(g);
			return Color.argb(a, r, g, b);
		}

		private static final float PI = 3.1415926f;

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			float x = event.getX() - CENTER_X;
			float y = event.getY() - CENTER_Y;
			boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mTrackingCenter = inCenter;
				if (inCenter) {
					mHighlightCenter = true;
					invalidate();
					break;
				}
			case MotionEvent.ACTION_MOVE:
				if (mTrackingCenter) {
					if (mHighlightCenter != inCenter) {
						mHighlightCenter = inCenter;
						invalidate();
					}
				} else {
					float angle = (float) java.lang.Math.atan2(y, x);
					// need to turn angle [-PI ... PI] into unit [0....1]
					float unit = angle / (2 * PI);
					if (unit < 0) {
						unit += 1;
					}
					mChangedPaint.setColor(interpColor(mColors, unit));
					mCenterPaint.setColor(mChangedPaint.getColor());
					invalidate();
				}
				break;
			case MotionEvent.ACTION_UP:
				if (mTrackingCenter) {
					if (inCenter) {
					}
					mTrackingCenter = false; // so we draw w/o halo
					invalidate();
				}
				break;
			}
			return true;
		}
	}

	public ColorPickerDialog(Context context,
			OnAttributeChangedListener listener, Paint initialPaint) {
		super(context);
		mListener = listener;
		mChangedPaint = initialPaint;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LinearLayout ColorSeekbarlayout = new LinearLayout(getContext());
		ColorSeekbarlayout.setOrientation(1);
		LayoutParams seekparam = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		ColorSeekbarlayout.setLayoutParams(seekparam);

		ArrayList<String> atts = new ArrayList<String>();
		atts.add("Pen");
		atts.add("Blush");

		Spinner AttsSpinner = new Spinner(getContext());
		AttsSpinner.setPrompt("Select Drawing Tool");

		ArrayAdapter<String> SpinnerAdapter = new ArrayAdapter<String>(
				getContext(), android.R.layout.simple_spinner_item, atts);
		AttsSpinner.setAdapter(SpinnerAdapter);

		AttsSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						TextView tv = (TextView) arg1;
						String Att = tv.getText().toString();

						if (Att == "Blush") {
							MaskFilter mBlur;
							mBlur = new BlurMaskFilter(10,
									BlurMaskFilter.Blur.NORMAL);
							mChangedPaint.setMaskFilter(mBlur);
						} else if (Att == "Pen") {
							mChangedPaint.setMaskFilter(null);
						} else
							;
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});

		ArrayAdapter<String> PositionAdapter = (ArrayAdapter<String>) AttsSpinner
				.getAdapter();
		if (mChangedPaint.getMaskFilter() != null) {
			int spinnerPosition = PositionAdapter.getPosition("Blush");
			AttsSpinner.setSelection(spinnerPosition);
		} else {
			int spinnerPosition = PositionAdapter.getPosition("Pen");
			AttsSpinner.setSelection(spinnerPosition);
		}

		mColorSeekAlpha = new SeekBar(getContext());
		mColorSeekRed = new SeekBar(getContext());
		mColorSeekBlue = new SeekBar(getContext());
		mColorSeekGreen = new SeekBar(getContext());

		mColorSeekAlpha.setMax(255);
		mColorSeekAlpha.setProgress(Color.alpha(mChangedPaint.getColor()));
		mColorSeekRed.setMax(255);
		mColorSeekRed.setProgress(Color.red(mChangedPaint.getColor()));
		mColorSeekBlue.setMax(255);
		mColorSeekBlue.setProgress(Color.blue(mChangedPaint.getColor()));
		mColorSeekGreen.setMax(255);
		mColorSeekGreen.setProgress(Color.green(mChangedPaint.getColor()));

		TextView alpha = new TextView(getContext());
		alpha.setText("Transparency");
		TextView red = new TextView(getContext());
		red.setText("Red");
		TextView blue = new TextView(getContext());
		blue.setText("Blue");
		TextView green = new TextView(getContext());
		green.setText("Green");

		ColorSeekbarlayout.addView(AttsSpinner);
		ColorSeekbarlayout.addView(alpha);
		ColorSeekbarlayout.addView(mColorSeekAlpha);
		ColorSeekbarlayout.addView(red);
		ColorSeekbarlayout.addView(mColorSeekRed);
		ColorSeekbarlayout.addView(blue);
		ColorSeekbarlayout.addView(mColorSeekBlue);
		ColorSeekbarlayout.addView(green);
		ColorSeekbarlayout.addView(mColorSeekGreen);

		LinearLayout SetColorlayout = new LinearLayout(getContext());
		SetColorlayout.setOrientation(0);

		SetColorlayout.addView(new ColorPickerView(getContext(), mChangedPaint
				.getColor()));
		SetColorlayout.addView(ColorSeekbarlayout);

		LinearLayout layout = new LinearLayout(getContext());
		layout.setOrientation(1);

		TextView thicker = new TextView(getContext());
		thicker.setText("Thick");

		mThickSeek = new SeekBar(getContext());
		mThickSeek.setMax(50);
		mThickSeek.setProgress((int) mChangedPaint.getStrokeWidth());
		mThickSeek.setOnSeekBarChangeListener(ThickSeekbarlistener);

		Button Confirm = new Button(getContext());
		Confirm.setText("Confirm");

		LayoutParams param;
		param = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		Confirm.setLayoutParams(param);
		Confirm.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mListener.attributeChanged(mChangedPaint);
				dismiss();
			}
		});
		layout.addView(SetColorlayout);
		layout.addView(thicker);
		layout.addView(mThickSeek);
		layout.addView(Confirm);
		setContentView(layout);
		setTitle("Pen Attribute");
	}

	// penThick
	private SeekBar.OnSeekBarChangeListener ThickSeekbarlistener = new OnSeekBarChangeListener() {
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
		}
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
		}
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			// TODO Auto-generated method stub
			mChangedPaint.setStrokeWidth(progress);
		}
	};

}
